package edu.itla.medifacil.persistence.managers;

import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;

import edu.itla.medifacil.persistence.entities.People;
import edu.itla.medifacil.persistence.entities.Test;
import edu.itla.medifacil.persistence.entities.TestResult;

public class TestResultManager {
	private EntityManager em = null;
	
	public TestResultManager() {
		this.em = Persistence.createEntityManagerFactory("MediFacil").createEntityManager();
	}
	
	public TestResult save( Map<String, String> parameters ){
		TestResult testResult = new TestResult();
		PersonManager personManager = new PersonManager();
		TestManager testManager = new TestManager();
		
		People patient = personManager.find( Integer.parseInt( parameters.get("patientId") ) ); 
		Test test = testManager.find( Integer.parseInt( parameters.get("testId") ) ); 
		String result = parameters.get("result");
		
		if( parameters.get("id") != null && parameters.get("id").trim().length() > 0 )
			testResult = this.find( Integer.parseInt(parameters.get("id")) );
		
		testResult.setPatient(patient);
		testResult.setTest(test);
		testResult.setResult(result);
		
		em.getTransaction().begin();
		em.persist( testResult );
		em.getTransaction().commit();
		
		return this.find( testResult.getId() );
	}
	
	public void delete( int testId ){
		em.getTransaction().begin();
		em.createQuery("DELETE FROM TestResult WHERE id="+testId).executeUpdate();
		em.getTransaction().commit();
	}

	public TestResult find( int testId ){
		em.clear();
		return em.find( TestResult.class, testId);
	}
	
	@SuppressWarnings("unchecked")
	public List<TestResult> findAll(){
		return (List<TestResult>) em.createQuery( "SELECT t FROM TestResult t").getResultList();
	}
	

}
